package engine.operators;

import java.util.List;

import engine.Operator;
import engine.Population;
import engine.PopulationEvaluator;

public class CombineOperatorsWithEvaluation<T> implements Operator<T> {

	private Operator<T> operator1;
	private Operator<T> operator2;
	private PopulationEvaluator<T> evaluator;

	public CombineOperatorsWithEvaluation(
			Operator<T> operator1,
			PopulationEvaluator<T> eval,
			Operator<T> operator2) {
		this.operator1 = operator1;
		this.evaluator = eval;
		this.operator2 = operator2;
	}

	@Override
	public Population<T> apply(Population<T> population) {
		Population<T> p1 = operator1.apply(population);
		Population<T> p2 = evaluator.apply(p1);
		Population<T> joinedPop = joinPopulations(population, p2);
		Population<T> p3 = operator2.apply(joinedPop);
		return p3;
	}

	private Population<T> joinPopulations(Population<T> population, Population<T> p2) {
		List<T> individuals = population.getIndividuals();
		List<T> joinedIndividuals = p2.getIndividuals();
		individuals.addAll(joinedIndividuals);
		return new Population<T>(individuals);
	}

}
